import { defineStore } from 'pinia';
import { ref } from 'vue';

// 定义日志存储
export const useLogStore = defineStore('log', () => {
  // 日志数组，最多存储1000条
  const logs = ref<string[]>([]);
  const MAX_LOGS = 1000;
  
  // 更新日志数据
  function updateLogs(newLogs: string[]) {
    logs.value = [...newLogs];
    // 确保日志数量不超过1000条
    if (logs.value.length > MAX_LOGS) {
      logs.value = logs.value.slice(logs.value.length - MAX_LOGS);
    }
  }
  
  // 添加单条日志
  function addLog(log: string) {
    logs.value.push(log);
    // 如果超过最大数量，移除最早的日志
    if (logs.value.length > MAX_LOGS) {
      logs.value.shift();
    }
  }
  
  // 清空所有日志
  function clearLogs() {
    logs.value = [];
  }
  
  // 初始化日志监听
  function initLogListener() {
    if (window.systemApp) {
      // 注册日志更新监听
      const unsubscribe = window.systemApp.onLogUpdate((newLogs) => {
        updateLogs(newLogs);
      });
      
      // 请求获取当前所有日志
      window.systemApp.requestLogs();
      
      return unsubscribe;
    }
    return () => {};
  }
  
  return {
    logs,
    updateLogs,
    addLog,
    clearLogs,
    initLogListener
  };
});